<template>
  <div class="user-manage">
    <h2 class="page-title">👥 用户管理</h2>

    <!-- 搜索和筛选 -->
    <el-card class="search-card">
      <el-form :model="queryParams" inline>
        <el-form-item label="角色类型">
          <el-select v-model="queryParams.role" placeholder="全部" clearable style="width: 120px">
            <el-option label="全部" value=""></el-option>
            <el-option label="普通用户" value="user"></el-option>
            <el-option label="管理员" value="admin"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="账号状态">
          <el-select v-model="queryParams.status" placeholder="全部" clearable style="width: 120px">
            <el-option label="全部" value=""></el-option>
            <el-option label="正常" :value="1"></el-option>
            <el-option label="禁用" :value="0"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="关键词">
          <el-input v-model="queryParams.keyword" placeholder="用户名/邮箱/昵称" clearable style="width: 200px"
            @keyup.enter="handleSearch" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">
            搜索
          </el-button>
          <el-button :icon="Refresh" @click="handleReset"> 重置 </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 用户表格 -->
    <el-card class="table-card">
      <el-table :data="tableData" v-loading="loading" border>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" width="150" />
        <el-table-column prop="nickname" label="昵称" width="150" />
        <el-table-column prop="email" label="邮箱" width="200" />
        <el-table-column prop="role" label="角色" width="100">
          <template #default="{ row }">
            <el-tag :type="getRoleType(row.role)">
              {{ row.role === 'admin' ? '管理员' : '普通用户' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ row.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="注册时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" :icon="Edit" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button :type="row.status === 1 ? 'warning' : 'success'" size="small"
              :icon="row.status === 1 ? Lock : Unlock" @click="handleToggleStatus(row)">
              {{ row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button type="danger" size="small" :icon="Delete" @click="handleDelete(row)" v-if="row.role !== 'admin'">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination class="pagination" :current-page="queryParams.page" :page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="total"
        @current-change="handlePageChange" @size-change="handleSizeChange" background />
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑用户" width="500px">
      <el-form :model="editForm" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="editForm.email" disabled />
        </el-form-item>
        <el-form-item label="角色">
          <el-radio-group v-model="editForm.role">
            <el-radio label="user">普通用户</el-radio>
            <el-radio label="admin">管理员</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="editForm.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveEdit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>


<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getUserList,
  updateUserStatus,
  updateUserRole,
  deleteUser
} from '@/api/user'
import {
  Search,
  Refresh,
  Edit,
  Delete,
  Lock,
  Unlock
} from '@element-plus/icons-vue'

// 表格数据
const tableData = ref([])
const loading = ref(false)
const total = ref(0)

// 查询参数
const queryParams = ref({
  page: 1,
  pageSize: 10,
  role: '', // 角色筛选：'' 全部，'user' 普通用户，'admin' 管理员
  status: '', // 状态筛选：'' 全部，1 正常，0 禁用
  keyword: '' // 搜索关键词
})

// 编辑对话框
const editDialogVisible = ref(false)
const editForm = ref({
  id: 0,
  username: '',
  email: '',
  role: '',
  status: 1
})

// 加载用户列表
const loadUserList = async () => {
  loading.value = true
  try {
    const result = await getUserList(queryParams.value)
    if (result.success) {
      tableData.value = result.data.list
      total.value = result.data.total
    } else {
      ElMessage.error(result.message || '加载用户列表失败')
    }
  } catch (error) {
    console.error('加载用户列表失败:', error)
    ElMessage.error('加载用户列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  queryParams.value.page = 1
  loadUserList()
}

// 重置搜索
const handleReset = () => {
  queryParams.value = {
    page: 1,
    pageSize: 10,
    role: '',
    status: '',
    keyword: ''
  }
  loadUserList()
}

// 分页变化
const handlePageChange = (page) => {
  queryParams.value.page = page
  loadUserList()
}

const handleSizeChange = (size) => {
  queryParams.value.pageSize = size
  queryParams.value.page = 1
  loadUserList()
}

// 切换用户状态
const handleToggleStatus = async (row) => {
  const newStatus = row.status === 1 ? 0 : 1
  const action = newStatus === 1 ? '启用' : '禁用'

  try {
    await ElMessageBox.confirm(
      `确定要${action}用户"${row.username}"吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const result = await updateUserStatus(row.id, newStatus)
    if (result.success) {
      ElMessage.success(`${action}成功`)
      loadUserList()
    } else {
      ElMessage.error(result.message || `${action}失败`)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('切换用户状态失败:', error)
      ElMessage.error(`${action}失败`)
    }
  }
}

// 编辑用户
const handleEdit = (row) => {
  editForm.value = {
    id: row.id,
    username: row.username,
    email: row.email,
    role: row.role,
    status: row.status
  }
  editDialogVisible.value = true
}

// 保存编辑
const handleSaveEdit = async () => {
  try {
    // 更新角色
    const roleResult = await updateUserRole(
      editForm.value.id,
      editForm.value.role
    )
    if (!roleResult.success) {
      ElMessage.error(roleResult.message || '更新角色失败')
      return
    }

    // 更新状态
    const statusResult = await updateUserStatus(
      editForm.value.id,
      editForm.value.status
    )
    if (!statusResult.success) {
      ElMessage.error(statusResult.message || '更新状态失败')
      return
    }

    ElMessage.success('更新成功')
    editDialogVisible.value = false
    loadUserList()
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  }
}

// 删除用户
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户"${row.username}"吗？此操作不可恢复！`,
      '警告',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'error'
      }
    )

    const result = await deleteUser(row.id)
    if (result.success) {
      ElMessage.success('删除成功')
      loadUserList()
    } else {
      ElMessage.error(result.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除用户失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN')
}

// 获取角色标签类型
const getRoleType = (role) => {
  return role === 'admin' ? 'danger' : 'primary'
}

// 获取状态标签类型
const getStatusType = (status) => {
  return status === 1 ? 'success' : 'info'
}

onMounted(() => {
  loadUserList()
})
</script>

<style scoped>
.user-manage {
  padding: 20px;
}

.page-title {
  margin: 0 0 20px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

/* 搜索卡片 */
.search-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

/* 表格卡片 */
.table-card {
  border-radius: 8px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .user-manage {
    padding: 10px;
  }
}
</style>
